#include <device/blkio.h>
#include <device/block.h>
#include <mm/valloc.h>
#include <status.h>

#define LOG_TAG "BLK_PART"
#include <log.h>

int blkpart_probe(device_t* dev) {
    u8* mbr = valloc(512);
    int errno;
    if ((errno = dev->read(dev, mbr, 0, 512)) < 0) {
        goto done;
    }

    if (mbr[510] != 0x55 || mbr[511] != 0xAA) {
        errno = ENODEV;
    }

    blk_dev_t* bdev = (blk_dev_t*)dev->impl;
    if (!bdev) return ENODEV;

    int partition_table_start = 0x1BE;
    for (int i = 0; i < 4; i++) {
        int offset = partition_table_start + i * 16;
        u8 *entry = mbr + offset;

        u8 boot_flag = entry[0];
        u8 partition_type = entry[4];
        
        uint32_t start_lba = *(uint32_t*)(entry + 8);
        uint32_t sector_count = *(uint32_t*)(entry + 12);

        if (partition_type == 0 || sector_count == 0) {
            continue;
        }

        u32 index = i + 1;
        u32 bootable = boot_flag == 0x80;
        if (partition_type == 0x05 || partition_type == 0x0F) {
            LOGW("Extended partition detected! Not support yet!\n");
        }

        blk_dev_t* bd = blk_mount_part(bdev, NULL, index, start_lba, start_lba + sector_count);
        bd->part_id = partition_type;
    }

done:
    return errno;
}